package com.dragon.mmochat.service;

import java.awt.Color;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dragon.mmochat.MmochatConstant;
import com.dragon.mmochat.MmochatMain;
import com.dragon.mmochat.message.Mmochat_11_1C;
import com.dragon.mmochat.message.Mmochat_11_1S;
import com.dragon.mmochat.message.Mmochat_11_2C;
import com.dragon.mmochat.message.Mmochat_11_2S;
import com.dragon.mmochat.message.Mmochat_11_5C;
import com.dragon.mmochat.message.Mmochat_11_5S;
import com.dragon.mmochat.message.Mmochat_5_1S;
import com.dragon.mmochat.message.Mmochat_SendSystenMsgToOtherServer;
import com.dragon.mmochat.model.MmochatLockChatData;
import com.dragon.mmochat.model.battle.record.MmochatBattleRecord;
import com.dragon.mmochat.model.enumType.MmochatPropType;
import com.dragon.mmochat.model.enumType.MmochatChatChannelType;
import com.dragon.mmochat.model.enumType.MmochatServerType;
import com.dragon.mmochat.model.gang.MmochatGang;
import com.dragon.mmochat.model.gang.MmochatGangMember;
import com.dragon.mmochat.model.kefu.MmochatChatInfo;
import com.dragon.mmochat.model.map.MmochatMap;
import com.dragon.mmochat.model.object.MmochatCommonObject;
import com.dragon.mmochat.model.object.MmochatPackageGrid;
import com.dragon.mmochat.model.role.MmochatPet;
import com.dragon.mmochat.model.role.MmochatPlayer;
import com.dragon.mmochat.util.MmochatUtil;
import com.skymobi.handler.SkymobiHandler;
import com.skymobi.service.SkymobiService;

public class MmochatChatService {
	private static Logger log = LoggerFactory
			.getLogger(MmochatChatService.class);

	// 世界聊天中的物品ID范围,1:>0为装备；2:=0为人物信息；3:-1至-1亿为宠物ID；4:<-1亿为战斗ID
	public static int baseBattleIdInChat = -100000000;

	// 最近10条聊天记录,供后台查看
	public static ConcurrentLinkedQueue<MmochatChatInfo> chatBuffer = new ConcurrentLinkedQueue<MmochatChatInfo>();
	// GM发布的所有系统消息
	public static ConcurrentLinkedQueue<String> gmSysMsg = new ConcurrentLinkedQueue<String>();

	// 最近一次独占的消息发布时间(3秒内玩家无法发消息)
	public static long lastLockTime = 0;

	public MmochatChatService() {
		// 保留最近10条聊天记录
		for (int i = 0; i < 10; i++) {
			chatBuffer.offer(new MmochatChatInfo());
		}
	}

	public static Object[] getChatBufferArray() {
		return chatBuffer.toArray();
	}

	// 11.1场景聊天
	@SkymobiService
	public void handleC_11_1(SkymobiHandler handler, Mmochat_11_1C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return;
		}

		String userMsg = req.getChatMsg();
		if (userMsg.contains("") || userMsg.contains("")
				|| userMsg.contains("") || userMsg.contains("")) {
			sendSystemMsgToPerson(me, "您的聊天内容中包含不可见字符!");
			return;
		}

		if (me.getMapId() != (int) req.getMapId()
				|| me.getLine() != (int) req.getLine()) {
			return;
		}

		int line = me.getLine();
		MmochatMap curMap = MmochatMapService.maps.get(me.getMapId());
		if (curMap == null) {
			// TODO:地图不存在,将角色移到默认地图
			return;
		}

		if (!me.getShowChatSet().get(MmochatChatChannelType.场景)) {
			me.getShowChatSet().put(MmochatChatChannelType.场景, true);
			sendSystemMsgToPerson(me, "您使用了场景聊天,场景频道自动开启!");
			try {
				MmochatDao.updateRoleChatSet(me);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// 向同地图内的同屏玩家下发场景聊天
		String msg = MmochatFilterService.getFilterString(userMsg);
		for (MmochatPlayer role : curMap.getLineRoleMap(line).values()) {
			try {
				if (role.getRoleId() != me.getRoleId()) {
					if (Math.abs(role.getX() - me.getX()) < MmochatConstant.screenWidth
							&& Math.abs(role.getY() - me.getY()) < MmochatConstant.screenHeight) {
						// 向同屏的其它玩家发送场景聊天
						if (role.isMicroNetFlowMode()) {
							continue;
						}
						if (!role.getShowChatSet().get(
								MmochatChatChannelType.场景)) {
							continue;
						}
						// 打怪时不接收玩家的聊天信息
						if (role.isInBattle() || role.isInWatchingBattle()) {
							continue;
						}
						Mmochat_11_1S pack = new Mmochat_11_1S();
						pack.setMapId(curMap.getMapId());
						pack.setLine((byte) line);
						pack.setRoleId((int) me.getRoleId());
						pack.setChatMsg(msg);
						pack.setSrcId(MmochatMain.getModuleInstID());
						pack.setDstId(MmochatConstant.getClientModuleId());
						pack.setUserConnInfo(role.getUserConnInfo());
						SkymobiHandler handle = MmochatHandle_SendChat
								.getCommonHandler();
						if (handle != null) {
							handle.pushSkymobiMessage(pack);
						}
					}
				}
			} catch (Exception e) {
			}
		}
	}

	// 11.5 队伍聊天
	@SkymobiService
	public void handleC_11_5(SkymobiHandler handler, Mmochat_11_5C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return;
		}
		// 队伍聊天
		String userMsg = req.getChatMsg();
		if (userMsg.contains("") || userMsg.contains("")
				|| userMsg.contains("") || userMsg.contains("")) {
			sendSystemMsgToPerson(me, "您的聊天内容中包含不可见字符!");
			return;
		}

		if (me.getShowChatSet().get(MmochatChatChannelType.队伍) != null
				&& !me.getShowChatSet().get(MmochatChatChannelType.队伍)) {
			me.getShowChatSet().put(MmochatChatChannelType.队伍, true);
			sendSystemMsgToPerson(me, "您使用了队伍聊天,队伍频道自动开启!");
			try {
				MmochatDao.updateRoleChatSet(me);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		String msg = MmochatFilterService.getFilterString(userMsg);
		List<MmochatPlayer> members = MmochatTeamService.getMyTeamMember(me);
		for (MmochatPlayer member : members) {
			if (member == me) {
				continue;
			}
			if (member.isMicroNetFlowMode()) {
				continue;
			}
			// if (!member.getShowChatSet().get(MmochatChatChannelType.队伍)) {
			// continue;
			// }
			Mmochat_11_5S pack = new Mmochat_11_5S();
			pack.setRoleId(me.getRoleId());
			pack.setName(me.getName());
			pack.setChatMsg(msg);
			MmochatUtil.sendCommonPack(member, pack);
		}
	}

	// 11.2 全服聊天
	// 世界聊天中的物品ID范围,1:>0为装备；2:-1至-1亿为宠物ID；3:<-1亿为战斗ID
	@SkymobiService
	public void handleC_11_2(SkymobiHandler handler, Mmochat_11_2C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return;
		}

		if (System.currentTimeMillis() - lastLockTime < MmochatConstant.systemChatLockTime) {
			// 独占消息时间内，其它玩家不能发消息
			return;
		}

		if (MmochatGmService.isSystemExit()) {
			sendSystemMsgToPerson(me, "服务器正在维护中，暂时不能发言!");
		}

		if (req.getType() != MmochatChatChannelType.帮派.getValue()) {
			MmochatLockChatData forbiddenChat = MmochatConstant.forbiddenRoleIdToChat
					.get(me.getRoleId());
			if (forbiddenChat != null) {
				// 被禁言了
				if (System.currentTimeMillis() > forbiddenChat.getFreeTime()) {
					// 禁言时间结束
					MmochatConstant.forbiddenRoleIdToChat
							.remove(me.getRoleId());
				} else {
					// 禁言了
					sendSystemMsgToPerson(me, MmochatUtil.wrapColor(
							forbiddenChat.getReason()
									+ "剩余禁言时间还有"
									+ ((forbiddenChat.getFreeTime() - System
											.currentTimeMillis()) / 1000 / 60)
									+ "分钟!", Color.yellow));
					return;
				}
			}
		}

		if (System.currentTimeMillis() - me.getLastTimeOfWorldChat() < MmochatConstant.minIntervalOfWorldChat) {
			// 发言太快了
			sendSystemMsgToPerson(me, MmochatUtil.wrapColor("您的发言太快了,发言间隔为"
					+ (MmochatConstant.minIntervalOfWorldChat / 1000) + "秒!",
					Color.yellow));
			return;
		}

		int addChatNum = (int) ((System.currentTimeMillis() - me
				.getLastTimeOfAddChatNum()) / MmochatConstant.intervalToAddWorldChat);
		if (addChatNum > 0) {
			long tick = me.getLastTimeOfAddChatNum() + addChatNum
					* MmochatConstant.intervalToAddWorldChat;
			me.setLastTimeOfAddChatNum(tick);
			me.addFreeWorldChatNum(addChatNum);
		}
		if (me.getFreeWorldChatNum() <= 0) {
			// 没有发言机会了
			sendSystemMsgToPerson(
					me,
					MmochatUtil
							.wrapColor(
									"您的发言太频繁了，请"
											+ ((me.getLastTimeOfAddChatNum()
													+ MmochatConstant.intervalToAddWorldChat - System
													.currentTimeMillis()) / MmochatConstant.MS_PER_SECOND)
											+ "秒后再发言!", Color.yellow));
			return;
		}

		if (MmochatMain.serverType == MmochatServerType.跨服战服务器) {
			if (req.getType() == MmochatChatChannelType.帮派.getValue()) {
				// 帮派频道
				MmochatChatService.sendSystemMsgToPerson(me, "跨服区内无法使用帮派频道!");
				return;
			}
		}

		MmochatGang myGang = null;
		// 道具:喇叭
		if (req.getType() == MmochatChatChannelType.喇叭.getValue()) {
			if (MmochatMain.serverType == MmochatServerType.跨服战服务器) {
				// 跨服服务器内消耗竞技点
				if (me.getPk_score() < MmochatConstant.speakerCostOfPkScore) {
					sendSystemMsgToPerson(me, "跨服区内喇叭聊天需要消耗"
							+ MmochatUtil.wrapColor(
									MmochatConstant.speakerCostOfPkScore
											+ "点竞技点", Color.yellow) + ",您当前只有"
							+ me.getPk_score() + "点竞技点。竞技点可以在比武场找传送人进行了解。");
					return;
				}
				me.addPk_score(-1 * MmochatConstant.speakerCostOfPkScore);
				try {
					MmochatMain.serverListDaoService.updatePkScore(me
							.getRoleId() % 10000000, me.getRegServerInstId(),
							me.getPk_score());
				} catch (Exception e) {
					e.printStackTrace();
				}
				sendSystemMsgToPerson(me, "您消耗了"
						+ MmochatConstant.speakerCostOfPkScore + "点竞技点"
						+ "进行了一次跨服区喇叭喊话!");
			} else {
				MmochatPackageGrid grid = me
						.getPackageGridOfObj(MmochatPropType.喇叭);
				if (grid == null) {
					sendSystemMsgToPerson(me, "喇叭聊天需要消耗"
							+ MmochatUtil.wrapColor("喇叭", Color.yellow)
							+ "道具,按9键打开"
							+ MmochatUtil.wrapColor("商城", Color.yellow)
							+ "即可购买喇叭!");
					return;
				}
				MmochatCommonObject prop = grid.getObject();
				if (prop == null || prop.isUsedOut()) {
					sendSystemMsgToPerson(me, "喇叭聊天需要消耗"
							+ MmochatUtil.wrapColor("喇叭", Color.yellow)
							+ "道具,按9键打开"
							+ MmochatUtil.wrapColor("商城", Color.yellow)
							+ "即可购买喇叭!");
					return;
				}
				prop.use(1);
				if (prop.isUsedOut()) {
					grid.setObject(null);
				}
				try {
					MmochatDao.updateMyPackage(me);
				} catch (Exception e) {
					e.printStackTrace();
					prop.use(-1);
					grid.setObject(prop);
					sendSystemMsgToPerson(me, "服务器忙,扣除喇叭失败,请稍候使用喇叭频道!");
					return;
				}
				// 更新包裹数据
				Mmochat_5_1S pack = new Mmochat_5_1S();
				pack.addGrid(grid);
				MmochatUtil.sendCommonPack(me, pack);
				MmochatStatisticsService.addPropCost(MmochatPropType.喇叭, 1);
			}
		} else if (req.getType() == MmochatChatChannelType.帮派.getValue()) {
			// 帮派频道
			if (!me.hasGang()) {
				sendSystemMsgToPerson(me, "您尚未加入帮派,无法使用此频道!");
				return;
			}
			myGang = MmochatGangService.getGangById(me.getGangId());
			if (myGang == null) {
				sendSystemMsgToPerson(me, "您尚未加入帮派,无法使用此频道!");
				return;
			}
		}

		String userMsg = req.getChatMsg();
		if (userMsg.contains("") || userMsg.contains("")
				|| userMsg.contains("") || userMsg.contains("")) {
			sendSystemMsgToPerson(me, "您的聊天内容中包含不可见字符!");
			return;
		}

		me.setLastTimeOfWorldChat(System.currentTimeMillis());

		// 扣除发言机会
		me.addFreeWorldChatNum(-1);

		String msg = MmochatFilterService.getFilterString(userMsg);

		// 消息预处理
		String tagBmp = "";
		Color color = Color.white;
		// 0:世界, 1:喇叭
		if (req.getType() == MmochatChatChannelType.世界.getValue()) {
			color = Color.white;
			tagBmp = MmochatUtil.wrapIcon(MmochatConstant.BMP_CHAT_WORLDTAG);
			MmochatChatInfo msgbak = new MmochatChatInfo();
			msgbak.setChatMsg("[世界]" + me.getName() + ":" + msg);
			msgbak.setRoleId(me.getRoleId());
			chatBuffer.poll();
			chatBuffer.offer(msgbak);
		} else if (req.getType() == MmochatChatChannelType.喇叭.getValue()) {
			color = Color.yellow;
			tagBmp = MmochatUtil.wrapIcon(MmochatConstant.BMP_CHAT_SPEAKERTAG);
			MmochatChatInfo msgbak = new MmochatChatInfo();
			msgbak.setChatMsg("[喇叭]" + me.getName() + ":" + msg);
			msgbak.setRoleId(me.getRoleId());
			chatBuffer.poll();
			chatBuffer.offer(msgbak);
		} else if (req.getType() == MmochatChatChannelType.帮派.getValue()) {
			color = new Color(88, 210, 1);
			tagBmp = MmochatUtil.wrapIcon(MmochatConstant.BMP_CHAT_GANGTAG);
		} else {
			return;
		}

		int msgEquipId = -1;
		int msgMapId = -1;
		int msgMapX = 0, msgMapY = 0;
		String msgBak;
		String worldMsg = msg, speakerMsg = msg;

		// #表1#~#表37# 替换成表情图标
		{
			Pattern equipPattern = Pattern.compile("#表[0-9]+#");
			Matcher matcher = equipPattern.matcher(msg);
			while (matcher.find()) {
				String equipStr = matcher.group();
				String equipPrueStr = equipStr.substring(2,
						equipStr.length() - 1);
				if (equipPrueStr.length() > 0) {
					try {
						int emotionId = Integer.parseInt(equipPrueStr);
						emotionId += MmochatConstant.BMP_EMOTION_1 - 1;
						if (emotionId >= MmochatConstant.BMP_EMOTION_1
								&& emotionId < MmochatConstant.BMP_EMOTION_MAX) {
							worldMsg = worldMsg.replaceFirst(equipStr,
									MmochatUtil.wrapIcon(emotionId));
							speakerMsg = speakerMsg.replaceFirst(equipStr,
									MmochatUtil.wrapIcon(emotionId));
						}
					} catch (NumberFormatException e) {
						e.printStackTrace();
					}
				}
			}
		}

		// #时间# 替换成当时系统时间
		try {
			if (worldMsg.contains("#时间#")) {
				SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
				String t = sdf.format(new Date());
				worldMsg = worldMsg.replaceFirst("#时间#", MmochatUtil.wrapColor(
						t, Color.green));
				speakerMsg = speakerMsg.replaceFirst("#时间#", MmochatUtil
						.wrapColor(t, Color.green));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// #录像#替换成战斗信息
		try {
			if (worldMsg.contains("#录像#")) {
				MmochatBattleRecord record = MmochatBattleService.battleRecords
						.get(me.getRecordBattleId());
				if (record != null) {
					record.setLastShowTime(System.currentTimeMillis());
					msgEquipId = baseBattleIdInChat + record.getId();
					String battleInfo = record.getName1()
							+ MmochatUtil
									.wrapIcon(MmochatConstant.BMP_EMOTION_32)
							+ record.getName2();
					worldMsg = worldMsg.replaceFirst("#录像#", MmochatUtil
							.wrapColor(record.getType().toString() + "录像:",
									Color.yellow)
							+ MmochatUtil.wrapBgIcon(
									MmochatConstant.BMP_CHAT_WHITETAG, Math
											.max(1, battleInfo.length() - 1))
							+ MmochatUtil.wrapColor(battleInfo, Color.black));
					speakerMsg = speakerMsg.replaceFirst("#录像#", MmochatUtil
							.wrapColor(record.getType().toString() + "录像:"
									+ battleInfo, Color.magenta));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (me.hasPropEffect(MmochatPropType.会员周卡.getEffectKey())) {
			// #当前坐标# 替换成实际坐标, 要求VIP
			MmochatMap curMap = MmochatMapService.getMapByMapId(me.getMapId());
			if (curMap != null) {
				String potisionMsg = curMap.getMapName();
				potisionMsg = potisionMsg.replaceAll("", "");
				potisionMsg = potisionMsg.replaceAll("", "");
				potisionMsg = potisionMsg.replaceAll("", "");
				potisionMsg = potisionMsg.replaceAll("", "");
				potisionMsg += (me.getLine() + 1) + "线";
				potisionMsg += "(" + me.getX() + "," + me.getY() + ")";
				potisionMsg = MmochatUtil.wrapColor(potisionMsg, Color.cyan);
				msgBak = worldMsg.replaceFirst("#当前坐标#", potisionMsg);
				if (!worldMsg.equals(msgBak)) {
					// 有坐标信息
					msgMapId = me.getMapId();
					msgMapX = me.getX();
					msgMapY = me.getY();
					worldMsg = msgBak;
					speakerMsg = speakerMsg.replaceFirst("#当前坐标#", potisionMsg);
				}
			}

			// #[0-9]+# 替换成物品名, 要求VIP
			Pattern equipPattern = Pattern.compile("#[0-9]+#");
			Matcher matcher = equipPattern.matcher(msg);
			if (matcher.find()) {
				String equipStr = matcher.group();
				String equipPrueStr = equipStr.substring(1,
						equipStr.length() - 1);
				if (equipPrueStr.length() > 0) {
					try {
						int gridId = Integer.parseInt(equipPrueStr);
						MmochatPackageGrid grid = me.getMyPackage().get(gridId);
						if (grid != null && grid.getObject() != null) {
							MmochatCommonObject obj = grid.getObject();
							if (obj != null) {
								msgEquipId = obj.getId();
								worldMsg = worldMsg
										.replaceFirst(
												equipStr,
												MmochatUtil
														.wrapBgIcon(
																MmochatConstant.BMP_CHAT_WHITETAG,
																obj
																		.getName()
																		.length() + 2)
														+ MmochatUtil
																.wrapColor(
																		"〖"
																				+ obj
																						.getName()
																				+ "〗",
																		Color.black));
								speakerMsg = speakerMsg.replaceFirst(equipStr,
										MmochatUtil.wrapColor(obj.getName(),
												obj.getColor()));
							}
						}
					} catch (NumberFormatException e) {
					}
				}
			} else {
				// 没有发送物品信息时，#宠#解析为参战宠物；#我#解析为人物属性。终端以查看物品来查看
				if (worldMsg.contains("#我#")) {
					msgEquipId = 0;
					worldMsg = worldMsg.replaceFirst("#我#", MmochatUtil
							.wrapBgIcon(MmochatConstant.BMP_CHAT_WHITETAG, 6)
							+ MmochatUtil.wrapColor("〖角色属性〗", Color.black));
					speakerMsg = speakerMsg.replaceFirst("#我#", MmochatUtil
							.wrapColor("〖角色属性〗", Color.yellow));
				} else if (worldMsg.contains("#宠#")) {
					MmochatPet pet = me.getPkPet();
					if (pet != null) {
						msgEquipId = -1 * pet.getId();
						String petName = pet.getPetTypeName();
						worldMsg = worldMsg.replaceFirst("#宠#", MmochatUtil
								.wrapBgIcon(MmochatConstant.BMP_CHAT_WHITETAG,
										petName.length() + 1)
								+ MmochatUtil.wrapColor("〖" + petName + "〗",
										Color.black));
						speakerMsg = speakerMsg.replaceFirst("#宠#", MmochatUtil
								.wrapColor("〖" + petName + "〗", Color.magenta));
					}
				}
			}
		}
		String userName = me.getName();
		if (MmochatMain.serverType == MmochatServerType.跨服战服务器) {
			userName += me.getCurChenHaoInfo() == null ? "" : "-"
					+ me.getCurChenHaoInfo();
		}

		String wholeScreenMsg = tagBmp
				+ MmochatUtil.wrapColor(userName + ":" + worldMsg, color);
		String partScreenMsg = MmochatUtil.wrapColor("[" + userName + "]:",
				new Color(209, 227, 54))
				+ speakerMsg;

		if (req.getType() == MmochatChatChannelType.喇叭.getValue()) {
			if (!me.getShowChatSet().get(MmochatChatChannelType.喇叭)) {
				me.getShowChatSet().put(MmochatChatChannelType.喇叭, true);
				sendSystemMsgToPerson(me, "您使用了喇叭聊天,喇叭频道自动开启!");
				try {
					MmochatDao.updateRoleChatSet(me);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else if (req.getType() == MmochatChatChannelType.世界.getValue()) {
			if (!me.getShowChatSet().get(MmochatChatChannelType.世界)) {
				me.getShowChatSet().put(MmochatChatChannelType.世界, true);
				sendSystemMsgToPerson(me, "您使用了世界聊天,世界频道自动开启!");
				try {
					MmochatDao.updateRoleChatSet(me);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else if (req.getType() == MmochatChatChannelType.帮派.getValue()) {
			if (!me.getShowChatSet().get(MmochatChatChannelType.帮派)) {
				me.getShowChatSet().put(MmochatChatChannelType.帮派, true);
				sendSystemMsgToPerson(me, "您使用了帮派聊天,帮派频道自动开启!");
				try {
					MmochatDao.updateRoleChatSet(me);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		// 下发消息
		Mmochat_11_2S pack = new Mmochat_11_2S();
		pack.setType(req.getType());
		pack.setEquipId(msgEquipId);
		pack.setMapId(msgMapId);
		pack.setX((short) msgMapX);
		pack.setY((short) msgMapY);

		if (req.getType() == MmochatChatChannelType.帮派.getValue()) {
			// 向本帮成员发送消息
			if (myGang != null) {
				for (MmochatGangMember member : myGang.getMembers().values()) {
					MmochatPlayer p = MmochatMainService.players.get(member
							.getRoleId());
					if (p != null) {
						if (p.isMicroNetFlowMode()) {
							continue;
						}
						// 打怪时不接收玩家的聊天信息
						if (p.isInBattle() || p.isInWatchingBattle()) {
							continue;
						}
						if (p.getShowChatSet().get(MmochatChatChannelType.帮派)) {
							pack.setLine((byte) me.getLine());
							pack.setRoleId(me.getRoleId());
							pack.setMsg(wholeScreenMsg);
							pack.setRollMsg(null);
							MmochatUtil.sendCommonPack(MmochatHandle_SendChat
									.getCommonHandler(), p, pack);
						}
					}
				}
			}
		} else {
			// 向所有同意接收消息的玩家发送聊天
			for (MmochatPlayer role : MmochatMainService.players.values()) {
				if (role.isMicroNetFlowMode()) {
					continue;
				}
				// 打怪时不接收玩家的聊天信息
				if (role.isInBattle() || role.isInWatchingBattle()) {
					continue;
				}
				pack.setLine((byte) me.getLine());
				pack.setRoleId(me.getRoleId());

				boolean send = false;

				if (req.getType() == MmochatChatChannelType.世界.getValue()) {
					if (role.getShowChatSet().get(MmochatChatChannelType.世界)) {
						if (role != me && !role.canReceiveWorldChat()) {
							send = false;
						} else {
							role.setLastTimeOfReceiveWorldChat(System
									.currentTimeMillis());
							pack.setMsg(wholeScreenMsg);
							pack.setRollMsg(null);
							send = true;
						}
					}
				} else if (req.getType() == MmochatChatChannelType.喇叭
						.getValue()) {
					if (role.getShowChatSet().get(MmochatChatChannelType.喇叭)) {
						pack.setMsg(wholeScreenMsg);
						pack.setRollMsg(partScreenMsg);
						send = true;
					}
				}

				if (send) {
					MmochatUtil.sendCommonPack(MmochatHandle_SendChat
							.getCommonHandler(), role, pack);
				}
			}
		}
	}

	// 下发系统消息
	public static void sendSystemMsg(String context) {
		if (context == null || context.length() == 0) {
			return;
		}
		Mmochat_11_2S pack = new Mmochat_11_2S();
		pack.setType(MmochatChatChannelType.系统.getValue());
		pack.setRoleId(-1);
		pack.setEquipId(-1);

		String wholeScreenMsg = MmochatUtil
				.wrapIcon(MmochatConstant.BMP_CHAT_SYSTEMTAG);
		wholeScreenMsg += MmochatUtil.wrapColor(context, new Color(250, 150,
				249));

		// 向所有玩家发送聊天
		lastLockTime = System.currentTimeMillis();
		for (MmochatPlayer p : MmochatMainService.players.values()) {
			// if (p.getShowChatSet().get(MmochatChatChannelType.系统)) {
			pack.setLine((byte) p.getLine());
			pack.setMsg(wholeScreenMsg);
			MmochatUtil.sendCommonPack(MmochatHandle_SendChat
					.getCommonHandler(), p, pack);
			// }
		}
	}

	// 带坐标信息的系统消息
	public static void sendSystemMsg(String context, int mapId, int x, int y) {
		if (context == null || context.length() == 0) {
			return;
		}
		Mmochat_11_2S pack = new Mmochat_11_2S();
		pack.setType(MmochatChatChannelType.系统.getValue());
		pack.setRoleId(-2);
		pack.setEquipId(-1);
		pack.setMapId(mapId);
		pack.setX((short) x);
		pack.setY((short) y);

		String wholeScreenMsg = MmochatUtil
				.wrapIcon(MmochatConstant.BMP_CHAT_SYSTEMTAG);
		wholeScreenMsg += MmochatUtil.wrapColor(context, new Color(250, 150,
				249));

		// 向所有玩家发送聊天
		lastLockTime = System.currentTimeMillis();
		for (MmochatPlayer p : MmochatMainService.players.values()) {
			// if (p.getShowChatSet().get(MmochatChatChannelType.系统)) {
			pack.setLine((byte) p.getLine());
			pack.setMsg(wholeScreenMsg);
			MmochatUtil.sendCommonPack(MmochatHandle_SendChat
					.getCommonHandler(), p, pack);
			// }
		}
	}

	// GM发布系统消息
	public static void sendSystemMsgByGm(String context, String gmName) {
		sendSystemMsg(context);

		Calendar cal = Calendar.getInstance();
		java.text.SimpleDateFormat sdf = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String cdate = sdf.format(cal.getTime());
		gmSysMsg.offer(new String(cdate + " " + gmName + ":" + context));
	}

	// 获取GM发布过的系统消息
	public static Object[] getGmSystemMsgLog() {
		return gmSysMsg.toArray();
	}

	// 向指定玩家下发系统消息
	public static void sendSystemMsgToPerson(MmochatPlayer p, String context) {
		if (context == null || context.length() == 0 || p == null) {
			return;
		}
		if (!p.getShowChatSet().get(MmochatChatChannelType.系统)) {
			return;
		}
		Mmochat_11_2S pack = new Mmochat_11_2S();
		pack.setType(MmochatChatChannelType.系统.getValue());
		pack.setRoleId(-1);
		pack.setEquipId(-1);

		String wholeScreenMsg = MmochatUtil
				.wrapIcon(MmochatConstant.BMP_CHAT_SYSTEMTAG);
		wholeScreenMsg += MmochatUtil.wrapColor(context, new Color(250, 150,
				249));

		pack.setLine((byte) p.getLine());
		pack.setMsg(wholeScreenMsg);
		MmochatUtil.sendCommonPack(p, pack);
	}

	// 向所有区服发送系统消息(不包括列表服务器)
	public static void sendSystemMsgToAllServer(String content) {
		if (content == null || content.length() == 0
				|| MmochatMain.serverListInfo == null) {
			return;
		}
		for (Entry<Integer, Integer> entry : MmochatMain.serverListInfo
				.entrySet()) {
			Integer serverId = entry.getKey();
			if (serverId == null) {
				continue;
			}
			Integer instId = entry.getValue();
			if (instId != null) {
				if (instId != MmochatMain.getModuleInstID()) {
					// 其它服
					Mmochat_SendSystenMsgToOtherServer pack = new Mmochat_SendSystenMsgToOtherServer(
							instId);
					pack.setSysInfo(content);
					MmochatUtil.sendMultiServerPack(pack);
				} else {
					// 本服
					sendSystemMsg(content);
				}
			}
		}
	}

	@SkymobiService
	public void handleC_SendSystenMsgToOtherServer(SkymobiHandler handler,
			Mmochat_SendSystenMsgToOtherServer req) {
		sendSystemMsg(req.getSysInfo());
	}
}
